/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.utils.AppUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 游家纨绔
 * @dateTime 2023-09-09 10:00
 * @apiNote TODO 支付宝支付控制器
 */
@Controller
public class PayController {

	@Resource
	private AlipayClient alipayClient;
	@Resource
	private AlipayTradePagePayRequest alipayTradePagePayRequest;

	/**
	 * 处理支付请求的方法
	 * 请求需要接受的参数：订单号  金额  名称  商品描述  表单中的其他参数
	 */
	@RequestMapping("/pay")
	public void pay(String WID_out_trade_no, String WID_subject, String WID_total_amount,
	                String WID_body, HttpServletResponse response) throws AlipayApiException, IOException {
		// 1、设置参数
		alipayTradePagePayRequest.setReturnUrl(AppUtils.return_url);
		// 1.1、设置异步返回路径(支付宝向我们的应用发送一个消息，支付成功还是支付失败的消息)
		alipayTradePagePayRequest.setNotifyUrl(AppUtils.notify_url);
		/** 1.2、设置其他请求参数
		 *  out_trade_no  商户订单号，由商家自定义，64个字符以内，仅支持字母、数字、下划线且需保证在商户端不重复，必填
		 *  total_amount  付款金额，必填
		 *  subject       订单标题。注意：不可使用特殊字符，如 /，=，& 等，必填
		 *  product_code  销售产品码，与支付宝签约的产品码名称。目前电脑支付场景下仅支持FAST_INSTANT_TRADE_PAY，必填
		 *  body          商品描述，选填
		 */
		alipayTradePagePayRequest.setBizContent(
				"{" +
						"\"out_trade_no\": \"" + WID_out_trade_no + "\"," +
						"\"total_amount\": \"" + WID_total_amount + "\"," +
						"\"subject\": \"" + WID_subject + "\"," +
						"\"product_code\": \"FAST_INSTANT_TRADE_PAY\"," +
						"\"body\": \"" + WID_body + "\"" +
						"}");
		// 2、发送请求。 这里返回的 Body 是一个字符串形式的 HTML
		String body = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
		// 3、相应的结果发送给前端
		response.setContentType("text/html;charset=utf-8");
		// 在页面上展示返回的 HTML(实际用户感知不到这个页面,直接被重定向到支付宝的网关[登录付款方账号])
		response.getWriter().println(body);
	}

}
